# -*- coding: utf-8 -*-
import requests
import smtplib
from ping3 import ping
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime


def nowTime():
    now = datetime.now()
    # 将时间格式化为字符串
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_time


def connect_to_server():
    smtp_server = "smtp.mxhichina.com"
    port = 80
    sender_email = "noreply@pingcl.com"
    password = "p2q7hDokTA%BpmG"

    server = smtplib.SMTP(smtp_server, port)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(sender_email, password)

    return server


def Send_Mail(messages):
    nowtime = nowTime()
    server = connect_to_server()

    sender_email = "noreply@pingcl.com"
    receiver_email = [
        "runfa.li@pingcl.com",
        # "taoming.zhou@pingcl.com",
    ]
    subject = f"香港图片服务器告警({nowtime})"
    # 使用HTML格式化消息内容
    message = f"""
    <html>
    <body>
    <p>您好！</p>
    <p>产生以下告警：</p>
    <p><strong>{messages}</strong></p>
    <p>请关注！</p>
    </body>
    </html>
    """

    email = MIMEMultipart()
    email["From"] = sender_email
    email["To"] = ", ".join(receiver_email)
    email["Subject"] = subject

    # 将MIMEText的类型从"plain"改为"html"
    email.attach(MIMEText(message, "html"))
    server.send_message(email)
    server.quit()


def test_webside(domain_name):
    nowtime = nowTime()
    # 增加重连次数
    requests.adapters.DEFAULT_RETRIES = 5
    # 关闭多余连接
    s = requests.session()
    s.keep_alive = False
    # 配置 url
    url = f"http://{domain_name}"
    # 配置 headers，关闭连接
    headers = {
        "Connection": "close",
    }
    try:
        # 测试域名连通性
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            print(f"{nowtime} {domain_name} 可正常访问！")
        else:
            message = f"*{nowtime}，{domain_name} 无法正常访问，状态码为：{response.status_code}。*"
            print(message)
            Send_Mail(message)
    except requests.exceptions.RequestException as e:
        message = f"*{nowtime}，尝试访问该站点时发生错误：{domain_name}: {str(e)}。*"
        print(message)
        Send_Mail(message)


def test_IP_A(
    ip_address,
    count=30,
    threshold_latency=100,
    threshold_packet_loss=10,
):
    nowtime = nowTime()
    try:
        # 测试A IP延迟和丢包率
        lost_packets = 0
        total_rtt = 0
        for _ in range(count):
            rtt = ping(ip_address)
            if rtt is not None:
                total_rtt += rtt * 1000
            else:
                lost_packets += 1

        packet_loss_percentage = round((lost_packets / count) * 100)
        avg_rtt_A = (
            total_rtt / (count - lost_packets) if count - lost_packets > 0 else None
        )
        avg_rtt = None
        if avg_rtt_A is not None:
            avg_rtt = int(avg_rtt_A)

        print(f"IP地址: {ip_address}")
        print(f"丢包率: {packet_loss_percentage}%")
        if avg_rtt is not None:
            nowtime = nowTime()
            print(f"平均值: {avg_rtt} ms")
            if avg_rtt > threshold_latency:
                message = f"*{nowtime}，{ip_address} 延迟平均值为：{avg_rtt} ms。*"
                print(message)
                Send_Mail(message)
        else:
            message = f"*{nowtime}，{ip_address} 无法 Ping 通。*"
            print(message)
            Send_Mail(message)

        if packet_loss_percentage > threshold_packet_loss:
            nowtime = nowTime()
            message = f"*{nowtime}，{ip_address} 丢包率为：{packet_loss_percentage}%。*"
            print(message)
            Send_Mail(message)
    except Exception as e:
        nowtime = nowTime()
        message = f"*{nowtime}，尝试测试 IP 时发生错误: {str(e)}。*"
        print(message)
        Send_Mail(message)


def test_IP_B(
    ip_address,
    count=30,
    threshold_latency=100,
    threshold_packet_loss=10,
):
    nowtime = nowTime()
    try:
        # 测试B IP延迟和丢包率
        lost_packets = 0
        total_rtt = 0
        for _ in range(count):
            rtt = ping(ip_address)
            if rtt is not None:
                total_rtt += rtt * 1000
            else:
                lost_packets += 1

        packet_loss_percentage = round((lost_packets / count) * 100)
        avg_rtt_A = (
            total_rtt / (count - lost_packets) if count - lost_packets > 0 else None
        )
        avg_rtt = None
        if avg_rtt_A is not None:
            avg_rtt = int(avg_rtt_A)

        print(f"IP地址: {ip_address}")
        print(f"丢包率: {packet_loss_percentage}%")
        if avg_rtt is not None:
            nowtime = nowTime()
            print(f"平均值: {avg_rtt} ms")
            if avg_rtt > threshold_latency:
                message = f"*{nowtime}，{ip_address} 延迟平均值为：{avg_rtt} ms。*"
                print(message)
                Send_Mail(message)
        else:
            nowtime = nowTime()
            message = f"*{nowtime}，{ip_address} 无法 Ping 通。*"
            print(message)
            Send_Mail(message)

        if packet_loss_percentage > threshold_packet_loss:
            nowtime = nowTime()
            message = f"*{nowtime}，{ip_address} 丢包率为：{packet_loss_percentage}%。*"
            print(message)
            Send_Mail(message)
    except Exception as e:
        message = f"*{nowtime}，尝试测试 IP 时发生错误: {str(e)}。*"
        print(message)
        Send_Mail(message)


# 调用函数测试域名连通性、IP延迟和丢包率
test_webside("consult-img.wenwo.com/fimg/529141296.jpg")
test_webside("wenwo-img.wenwo.com/fimg/529141296.jpg")
test_webside("103.233.10.145/fimg/529141296.jpg")
test_webside("pic-img.wenwo.com/fimg/529141296.jpg")
test_IP_A(
    "103.233.10.138",
    count=30,
    threshold_latency=100,
    threshold_packet_loss=10,
)
test_IP_B(
    "103.233.10.145",
    count=30,
    threshold_latency=100,
    threshold_packet_loss=10,
)
